using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace CGF
{
    public class TextureFontCreatorOnMultiSprite : MonoBehaviour
    {
        [MenuItem("Assets/创建位图字体（Multiple Sprite）")]
        private static void CreateFont()
        {
            Object[] objs = Selection.GetFiltered(typeof(Texture2D), SelectionMode.Assets);
            if (objs.Length == 0)
            {
                EditorUtility.DisplayDialog("提示", "请选择一张分割好的 Multiple Sprite 图片", "确定");
                return;
            }
            if (objs.Length > 1)
            {
                EditorUtility.DisplayDialog("提示", "只能选择一张图片", "确定");
                return;
            }
            Object o = objs[0];
            if (o.GetType() != typeof(Texture2D))
            {
                EditorUtility.DisplayDialog("提示", "请选择一张分割好的 Multiple Sprite 图片", "确定");
                return;
            }

            string selectionPath = AssetDatabase.GetAssetPath(o);
            string selectionExt = Path.GetExtension(selectionPath);
            if (selectionExt.Length == 0)
            {
                return;
            }
            string loadPath = selectionPath.Remove(selectionPath.Length - selectionExt.Length);
            string fontPathName = loadPath + ".fontsettings";
            string matPathName = loadPath + ".mat";
            float lineSpace = 0.1f;
            Object[] spriteObjs = AssetDatabase.LoadAllAssetsAtPath(selectionPath);
            List<Sprite> sprites = new List<Sprite>();
            foreach (var spriteObj in spriteObjs)
            {
                if (spriteObj && spriteObj.GetType() == typeof(Sprite))
                {
                    sprites.Add(spriteObj as Sprite);
                }
            }
            if (sprites.Count > 0)
            {
                Texture2D tex = o as Texture2D;
                Material mat;
                if (File.Exists(matPathName))
                {
                    mat = AssetDatabase.LoadAssetAtPath<Material>(matPathName);
                }
                else
                {
                    mat = new Material(Shader.Find("GUI/Text Shader"));
                    AssetDatabase.CreateAsset(mat, matPathName);
                }
                mat.SetTexture("_MainTex", tex);
                Font font;
                if (File.Exists(fontPathName))
                {
                    font = AssetDatabase.LoadAssetAtPath<Font>(fontPathName);
                }
                else
                {
                    font = new Font();
                    AssetDatabase.CreateAsset(font, fontPathName);
                }
                font.material = mat;
                CharacterInfo[] characterInfo = new CharacterInfo[sprites.Count + 1];
                for (int i = 0; i < sprites.Count; i++)
                {
                    if (sprites[i].rect.height > lineSpace)
                    {
                        lineSpace = sprites[i].rect.height;
                    }
                }
                for (int i = 0; i < sprites.Count; i++)
                {
                    Sprite spr = sprites[i];
                    CharacterInfo info = new CharacterInfo();
                    info.index = (int)spr.name[spr.name.Length - 1];
                    Rect rect = spr.rect;
                    float pivot = spr.pivot.y / rect.height - 0.5f;
                    if (pivot > 0)
                    {
                        pivot = -lineSpace / 2 - spr.pivot.y;
                    }
                    else if (pivot < 0)
                    {
                        pivot = -lineSpace / 2 + rect.height - spr.pivot.y;
                    }
                    else
                    {
                        pivot = -lineSpace / 2;
                    }
                    int offsetY = (int)(pivot + (lineSpace - rect.height) / 2);
                    //设置字符映射到材质上的坐标  
                    info.uvBottomLeft = new Vector2((float)rect.x / tex.width, (float)(rect.y) / tex.height);
                    info.uvBottomRight = new Vector2((float)(rect.x + rect.width) / tex.width, (float)(rect.y) / tex.height);
                    info.uvTopLeft = new Vector2((float)rect.x / tex.width, (float)(rect.y + rect.height) / tex.height);
                    info.uvTopRight = new Vector2((float)(rect.x + rect.width) / tex.width, (float)(rect.y + rect.height) / tex.height);
                    //设置字符顶点的偏移位置和宽高  
                    info.minX = 0;
                    info.minY = -(int)rect.height - offsetY;
                    info.maxX = (int)rect.width;
                    info.maxY = -offsetY;
                    //设置字符的宽度  
                    info.advance = (int)rect.width;
                    characterInfo[i] = info;
                }
                CharacterInfo einfo = new CharacterInfo();
                einfo.index = (int)(" ")[0];
                einfo.advance = (int)sprites[0].rect.width;
                characterInfo[sprites.Count] = einfo;

                font.characterInfo = characterInfo;
                EditorUtility.SetDirty(font);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();

                Debug.Log("Max Height：" + lineSpace + "  Prefect Height：" + (lineSpace + 2));
            }
            else
            {
                Debug.LogError("图片必须切割好 Multiple Sprite");
            }
        }
    }
}